<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData:{
      type: Array,
      default(){
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions();
    },
    setOptions() {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          top: 20,
          left: 10,
          right: 30,
          bottom: 20,
          containLabel: true,
        },
        xAxis: [{
          type: 'value',
          minInterval: 1,
          axisLabel:{
            fontSize: 15
          },
          splitArea: {
            show: false
          }
        }],
        yAxis: {
          axisLabel:{
            fontSize: 15,
            formatter(value) {
              if(value.length > 18) return value.slice(0,18) + '...'
              return value
            }
          },
          minInterval: 10,
          type: 'category',
          data: this.chartData.map(item => item.label),
        },
        series: [
          {
            name: '点击次数',
            type: 'bar',
            color: '#5ab1ef',
            barWidth: this.chartData.length <= 8 ? 30 : 25,
            data: this.chartData.map(item => item.num),
            animationEasing: 'cubicInOut',
            animationDuration: 3000
          }
        ],
      })
    }
  }
}
</script>
